package icu.shaoyayu.common.security.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import icu.shaoyayu.common.utll.ReturnUtil;
import icu.shaoyayu.common.utll.exception.CustomExceptionType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author shaoyayu
 * readme ：
 * 没有登录或则token失效，返回的结果
 */
@Component
public class RestAuthorizationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setCharacterEncoding("utf8");
        httpServletResponse.setContentType("application/json");
        PrintWriter out = httpServletResponse.getWriter();
        out.write(new ObjectMapper().writeValueAsString(ReturnUtil.error(CustomExceptionType.AUTHORITY_AUTHENTICATION_ERROR)));
        out.flush();
        out.close();
    }
}
